//Leaened：
//1. 客户端发给服务器的应该是个包, 同理收到的也是包！
//2. 不符合协议的输入的差错处理可以直接在客户端做，而不要交给Encode了！
#include "Socket.hpp"
#include "Protocol.hpp"

void Enter(string& ip, uint16_t port)
{
    Sock sock;

    sock.Socket();
    sock.Connect(ip, port);
    int fd = sock.GetFd();
    while(1)
    {
        cout << "Please Enter@ " ;
        int cnt = 3;
        string msg;
        getline(cin,msg);
        if(msg.size() < 5)
        {
            log(Warning,"invalid format!");
            continue;
        }

        string sendpackage;
        if(!Encode(msg, &sendpackage))
        {
            log(Warning, "invalid format");
            exit(-1);
        }

        write(fd, sendpackage.c_str(), sendpackage.size());

        char recvbuff[128] = {0};
        read(fd, recvbuff, sizeof(recvbuff));
        
        string recvpackage(recvbuff);
        string contents;
        Decode(recvpackage, &contents);
        cout << "result: " << contents << endl;        
    }

}

void Rand(string& ip, uint16_t port)
{
    string opers = "+-*/%^&";
    while(1)
    {
        cout << "----------------------------------------"<<endl;
        Sock sock;
        sock.Socket();
        sock.Connect(ip, port);
        int fd = sock.GetFd();

        int left = rand() % 10;
        int right = rand() % 10;
        char op = opers[rand() % opers.size()];

        Request req(left,right,op);        
        string contents;
        if(!req.Serialization(&contents))
        {
            log(Warning, "invalid format");
        }
        string package;
        Encode(contents,&package);
        // package += package;
        // package += package;
        
        write(fd,package.c_str(),package.size());
        //cout << "package is "  << '\n' << package;
        write(fd,package.c_str(),package.size());
        //cout << "package is "  << '\n'<< package;
        write(fd,package.c_str(),package.size());
        //cout << "package is "  << '\n'<< package;
        write(fd,package.c_str(),package.size());
        //cout << "package is "  << '\n'<< package;
        
        //close(fd);

        char recvbuff[1280] = {0};
        while(1)
        {
            int n;
            n = read(fd, recvbuff, sizeof(recvbuff));
            if(n > 0)
            {
                string recvpackage(recvbuff);
                contents = "";
                Decode(recvpackage, &contents);
                cout << "result: " << contents << endl;                  
            }
            else
            {
                break;
            }
            memset(recvbuff,0,sizeof(recvbuff));      
            sleep(1);   
        }

        cout << "----------------------------------------"<<endl;
        sleep(1);
    }

}

//./calclient ip port
int main(int argc, char* argv[])
{
    srand(time(0));
    if(argc < 3)
    {
        exit(-1);
    }

    string ip = string(argv[1]);
    uint16_t port = stoi(argv[2]);

    //do..
    Rand(ip,port);
    
    return 0;
}